﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace HNet
{
    public class RemoteMethod
    {
        public const string BytesMethName = "BytesMeth";

        private class Function
        {
            public Action<byte[]> Method;
            public object Belonger;

            public Function(Action<byte[]> method, object belonger)
            {
                Method = method;
                Belonger = belonger;
            }
        }

        //比特流函数字典
        private Dictionary<string, Function> _bytesMethDic = new Dictionary<string, Function>();

        public void RegisterBytesMeth(string name, Action<byte[]> meth, object belonger)
        {
            if (_bytesMethDic.ContainsKey(name))
            {
                _bytesMethDic[name] = new Function(meth, belonger);
            }
            else
            {
                _bytesMethDic.Add(name, new Function(meth, belonger));
            }
        }

        //从字典中获取函数
        public Action<byte[]> GetBytesMeth(string name)
        {
            if (_bytesMethDic.ContainsKey(name))
            {
                if (_bytesMethDic[name].Belonger != null)
                {
                    return _bytesMethDic[name].Method;
                }
                else
                {
                    _bytesMethDic.Remove(name);
                    return null;
                }
            }
            return null;
        }

        //直接调用函数
        public void ExecutionBytesMeth(Message msg)
        {
            string name = ProtocolBuffer.DeSerialize<string>(msg.DataList[0]);
            byte[] param = ProtocolBuffer.DeSerialize<byte[]>(msg.DataList[1]);

            Action<byte[]> meth = GetBytesMeth(name);

            if (meth != null)
            {
                meth(param);
            }
        }

        //生成远程协议用，不会更改消息的发送和接收
        public static void GenerateBytesMeth(string name, byte[] param, ref Message msg)
        {
            msg.Type = Message.MsgType.Remote;
            msg.Data = ProtocolBuffer.Serialize<string>(BytesMethName);
            List<byte[]> dataList = new List<byte[]>();
            dataList.Add(ProtocolBuffer.Serialize<string>(name));
            dataList.Add(ProtocolBuffer.Serialize<byte[]>(param));
            msg.DataList = dataList;
        }
    }
}